<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" type="text/css" href="css/reset.css"/>
		<link rel="stylesheet" type="text/css" href="css/tao.css"/>
		<link rel="stylesheet" type="text/css" href="css/etao-top-nav-wrap.css"/>
		<link rel="stylesheet" type="text/css" href="css/yitao_header.css"/>
		 <link rel="stylesheet" type="text/css" href="css/reset.css">
		<style type="text/css">
		  	table img{
		  		width: 150px;
		  		height:120px;
		  	}
		</style>
	</head>
	<body>
		<div id="etao-top-nav-wrap">
			<div id="etao-top-navclearfix">
				<div id="top-nav-loginfl">
					    <a href="index.html">首页</a>
    <a href="register.html" name="register" class="register">注册</a>
    <a href="login.html" name="login" class="login">登录</a>
    <a href="#" name="username" class="username">asdfghjkl1</a>
    <!-- 可以在a链接里面写javascript代码，在href属性中以javascript:开头，后面写js代码 -->
    <a href="javascript:localStorage.clear(); location.reload();" class="logout">退出</a>
    <script>
      //判断用户名如果存在, 则显示用户名并显示退出按钮, 否则显示注册和登录
      if (localStorage.username) {
        var oUsername = document.querySelector('a[name=username]');
        var oLogout = document.querySelector('.logout');
        oUsername.innerText = localStorage.username;
        oUsername.style.display = 'inline';
        oLogout.style.display = 'inline';
      } else {
        var oRegister = document.querySelector('.register');
        var oLogin = document.querySelector('.login');
        oRegister.style.display = 'inline';
        oLogin.style.display = 'inline';
      }
    </script>
				</div>
				<div id="top-tipfl">欢迎来到一淘网，阿里巴巴旗下生活省钱利器！</div>
			</div>
		</div>
		<div id="yitao_header">
			<div id="yitao_header_middle">
				<div id="middle_img">
					<a href="index.html">
						<img src="img/TB1yRiUQVXXXXaAXFXXXXXXXXXX-620-220.png"/>
					</a>
				</div>
				<div id="yitao_middle_search">
    				<input class="search-text" id="search-text" type="text" placeholder="购物拿返利，手机购物更便捷">
					<div id="yitao_middle_search_right">
						<input type="submit" name="right_search" id="right_search" value="" />
					</div>
					</div>
					<div id="middle_right_img">
						<a href="">
							<img src="img/TB13Gu9OFXXXXc1apXXXXXXXXXX-620-220.png"/>
						</a>
				</div>
			</div>
		</div>
  <!--<header>-->
  	<div class="header-container">


    <!--<a href="cart.html">购物车</a>
    <a href="order.html">我的订单</a>-->
    <script src="js/myajax.js" charset="utf-8"></script>
    <!--<input id="search" type="text" placeholder="请输入要搜索的内容">-->
    <script>
      var oSearch = document.querySelector("#search");
      oSearch.onkeyup = function(event) {
        if (event.keyCode === 13) {
          location.href = 'search.html?search_text='+this.value;
        }
      }
    </script>
	<div class="daohang">
    		<ul id="cat" class="cat"></ul>
		</div>
    <script>
    var oCat = document.querySelector('#cat');
    myajax.get('http://h6.duchengjiu.top/shop/api_cat.php', {}, function(error, responseText){
        var json = JSON.parse(responseText);//返回的整个json对象
        var data = json.data;//json对象当中的data是一个数组
        for (var i = 0; i < data.length; i++) {
          var obj = data[i];//数组里面的每一项是一个商品分类的对象
          oCat.innerHTML += `<li><a href="list.html?cat_id=${obj.cat_id}">${obj.cat_name}</a></li>`;
        }
    });
    </script>
  </div>
  <!--</header>-->

  <main>
    <table>
      <tr>
        <td>商品ID</td>
        <td>图片</td>
        <td>名称</td>
        <td>数量</td>
        <td>单价</td>
        <td>总价</td>
        <td>操作</td>
      </tr>
    </table>
    <div>小计：<span id="sum">0</span> <input type="button" id="clear-cart" value="清空购物车"> <a href="checkout.html">结算</a></div>
  </main>
  <script src="js/myajax.js" charset="utf-8"></script>
  <script>
    var oTable = document.querySelector('table');
    var oSum = document.querySelector('#sum');
    myajax.get('http://h6.duchengjiu.top/shop/api_cart.php', {token: localStorage.token}, function(err, responseText){
      var json = JSON.parse(responseText);
      console.log(json);
      var data = json.data;
      for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        //一件商品的总价
        obj.goods_sum = obj.goods_price * obj.goods_number;
        oTable.innerHTML += `
                          <tr>
                            <td name="goods_id">${obj.goods_id}</td>
                            <td><img src="${obj.goods_thumb}" ></td>
                            <td>${obj.goods_name}</td>
                            <td><input data-id="${obj.goods_id}" type="number" name="number" min="1" max="10" value="${obj.goods_number}" /></td>
                            <td>￥${obj.goods_price}</td>
                            <td name="sum">￥${obj.goods_sum}</td>
                            <td><input data-id="${obj.goods_id}" type="button" name="delete" value="删除"></td>
                          </tr>
                          `;
      }
      getSum();
    });

    oTable.onchange = function(event) {
      event = event || window.event;
      var target = event.target || event.srcElement;
      if (target.name === 'number') {
        //如果输入的内容不是数字，我们默认改成1
        if (isNaN(parseInt(target.value))) {
          target.value = 1;
        }
        console.log(target.value, target.dataset.id);
        //得到商品的ID
        var goods_id = target.dataset.id;
        //得到商品的数量
        var number = target.value;
        //请求api修改购买的商品数量
        myajax.post('http://h6.duchengjiu.top/shop/api_cart.php?token='+localStorage.token,
        {goods_id, number},
        function(err, responseText) {
          var json = JSON.parse(responseText);
          console.log(json);
          if (json.code === 0) {
            // alert('更新购物车成功');
            //修改总价和小计
            //得到当前商品的价格
            var goods_price = parseInt(target.parentNode.nextElementSibling.innerText);
            //修改单个商品的总价：数量 * 价格
            target.parentNode.nextElementSibling.nextElementSibling.innerText = parseInt(target.value) * goods_price;
            //显示总价
            getSum();
          }
        })
      }
    }
    oTable.addEventListener('click', function(event){
      event = event || window.event;
      var target = event.target || event.srcElement;
      if (target.name === 'delete') {
        if (!confirm('确认要删除吗')) { //当你选择的是取消则不执行任何事情
          return;
        }
        //得到商品ID
        var goods_id = target.dataset.id;
        var number = 0;
        myajax.post('http://h6.duchengjiu.top/shop/api_cart.php?token='+localStorage.token,
        {goods_id, number},
        (err, responseText) => {
          var json = JSON.parse(responseText);
          console.log(json);
          if (json.code === 0) {
            // alert('更新购物车成功');
            //删除整个TR
            var tr = target.parentNode.parentNode;
            tr.parentNode.removeChild(tr);
            //显示总价
            getSum();
          }
        })
      }
    });

    var oClearCart = document.querySelector('#clear-cart');
    oClearCart.onclick = () => {
      if (!confirm('确认要清空整个购物车吗？')) {
        return;
      }
      //得到所有的商品ID
      var oGoodsIds = document.querySelectorAll('td[name=goods_id]');
      for (var i = 0; i < oGoodsIds.length; i++) {
        var td = oGoodsIds[i];
        var goods_id = parseInt(td.innerText);
        var number = 0;
        (function(td){
          myajax.post('http://h6.duchengjiu.top/shop/api_cart.php?token='+localStorage.token,
          {goods_id, number},
          (err, responseText) => {
            var json = JSON.parse(responseText);
            console.log(json);
            if (json.code === 0) {
              // alert('更新购物车成功');
              //删除整个TR
              var tr = td.parentNode;
              tr.parentNode.removeChild(tr);
              //显示总价
              getSum();
            }
          });
        })(td);
      }
    }

    //显示出总价
    function getSum() {
      var oSums = document.querySelectorAll('td[name=sum]');
      var sum = 0;
      for (var i = 0; i < oSums.length; i++) {
        sum += parseInt(oSums[i].innerText.substr(1));
      }
      localStorage.sum = sum;
      oSum.innerText = "￥" + sum;
    }
  </script>
	</body>
</html>
